package com.sa07.ui.config;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.jdom2.Document;
import org.jdom2.Element;

import com.sa07.config.XmlConfigInit;
import com.sa07.ui.bean.ConfigConstTag;
import com.sa07.ui.bean.Menu;
import com.sa07.ui.bean.MenuItem;

/**
 * 菜单配置初始化
 * 
 * @author Long.shangbo
 * 
 *         2014-2-15 上午12:29:12
 */
public class MenuConfigInit extends XmlConfigInit {

	/**
	 * 菜单配置文件
	 */
	private static final String MENU_CONFIG_FILE = "menu.xml";

	@Override
	protected InputStream getConfigInputStream() {
		return MenuConfigInit.class.getResourceAsStream(MENU_CONFIG_FILE);
	}

	@Override
	protected void analyzeDocment(Document doc) {
		Element rootEle = doc.getRootElement();
		List<Element> menuEles = rootEle.getChildren(ConfigConstTag.MENU_TAG);
		List<Menu> menus = new ArrayList<Menu>();

		if (menuEles != null && !menuEles.isEmpty()) {
			Menu menu = null;

			for (Element menuEle : menuEles) {
				if (menuEle != null) {
					menu = new Menu();
					menu.setLabel(menuEle
							.getAttributeValue(ConfigConstTag.LABEL_ATTR));

					// 解析菜单项
					AnalyseMenuItems(menu, menuEle);
					menus.add(menu);
				}
			}
		}

		// 保存配置
		MenuConfig.INSTANCE.init(menus);
	}

	/**
	 * 解析菜单项
	 * 
	 * @param menu
	 * @param menuEle
	 */
	private void AnalyseMenuItems(Menu menu, Element menuEle) {
		List<MenuItem> menuItems = null;
		MenuItem menuItem = null;
		List<Element> menuItemEles = menuEle
				.getChildren(ConfigConstTag.MENU_ITEM_TAG);

		if (menuItemEles != null && !menuItemEles.isEmpty()) {
			menuItems = new ArrayList<MenuItem>();

			for (Element menuItemEle : menuItemEles) {
				if (menuItemEle != null) {
					menuItem = new MenuItem();
					menuItem.setLabel(menuItemEle
							.getAttributeValue(ConfigConstTag.LABEL_ATTR));
					menuItem.setHandlerClass(menuItemEle
							.getAttributeValue(ConfigConstTag.HANDLER_CLASS_ATTR));
					menuItems.add(menuItem);
				}
			}
			menu.setItems(menuItems);
		}
	}

}
